package com.united.ucts.common.plugin.security;

import com.united.frame.common.constant.AuthConstant;
import com.united.ucts.modules.auth.domain.MyUserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义的JWT内容增强器
 *
 * @author hudan
 * @version 1.0
 * @filename JwtTokenEnhancer.java
 * @copyright <a href="www.united.cn">www.united.cn</a>
 * @date 2019-10-10
 */
@Component
public class JwtTokenEnhancer implements TokenEnhancer {

    /**
     * 重写oauth的token内容
     * 将自定义的信息设置到JWT中
     *
     * @param accessToken    oauth的访问token
     * @param authentication 授权认证对象
     * @return 重写后的JWT内容Token对象
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        // 得到当前登录用户信息
        MyUserDetails myUserDetails = (MyUserDetails) authentication.getPrincipal();

        // 把用户ID设置到JWT中
        Map<String, Object> userDataMap = new HashMap<>(2);
        userDataMap.put(AuthConstant.JWT_ID, myUserDetails.getId());
        userDataMap.put(AuthConstant.JWT_CLIENT_ID, myUserDetails.getClientId());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(userDataMap);
        return accessToken;
    }
}